package gui;

import etc.PlayerStats;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import templates.Tower;
import templates.TowerTemplate;

public class SelectionPane extends JPanel implements Observer{
	private BuyPanel buypanel;
	private SelectPanel selectpanel;
	private Selection selection;

	public SelectionPane(Selection sel, PlayerStats ps) {
		super(new GridLayout(1,1));
		sel.addObserver(this);
		selection = sel;
		buypanel = new BuyPanel();
		selectpanel = new SelectPanel(ps);
	}

	@Override
	public void update(Observable obs, Object arg1) {
		Selection s = (Selection)obs;
		this.removeAll();

		if (s.type() == Selection.BUY) {
			TowerTemplate tt = s.getTemplate();
			buypanel.set(tt);
			this.add(buypanel);
		} else {
			Tower t = s.getTower();
			selectpanel.set(t);
			this.add(selectpanel);
		}
		this.repaint();
		this.validate();
	}
	
	class BuyPanel extends JPanel {
		JLabel icon, cost, power, reload, range;
		
		
		public BuyPanel() {
			super(new GridLayout(5,2));
			icon = new JLabel();
			cost = new JLabel();
			power = new JLabel();
			reload = new JLabel();
			range = new JLabel();
			add(icon);
			add(cost);
			add(power);
			add(reload);
			add(range);
		}
		
		public void set(TowerTemplate t) {
			icon.setIcon(t.icon);
			icon.setText(t.name);
			cost.setText("cost: "+ t.cost);
			power.setText("power: "+ t.power);
			reload.setText("reload: "+ t.reload);
			range.setText("range: "+ t.range);
		}
	}
	
	class SelectPanel extends JPanel implements ActionListener {
		Map<JButton, TowerTemplate> upg;
		Tower tower;
		JLabel icon;
		private PlayerStats ps;
		
		public SelectPanel(PlayerStats ps) {
			super(new GridLayout(5,2));
			this.ps = ps;
			upg = new HashMap<JButton, TowerTemplate>();
			icon = new JLabel();
			add(icon);
		}
		
		public void set(Tower t) {
			tower = t;
			TowerTemplate tt = t.getTemplate();
			icon.setIcon(tt.icon);
			icon.setText(tt.name +", "+ t.toString());
			for (JButton b: upg.keySet()) {
				remove(b);
			}
			upg.clear();
			for (TowerTemplate up: tt.upgrades) {
				JButton b = new JButton();
				b.setIcon(up.icon);
				b.setText(up.name +", "+ up.cost +"sek");
				b.addActionListener(this);
				add(b);
				upg.put(b, up);
			}
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			TowerTemplate temp = upg.get(e.getSource());
			if (ps.cash >= temp.cost){ 
//				tower.upgrade(temp);
				selection.set(tower);
				ps.cash -= temp.cost;
				ps.upd();
			}
		}
		
	}
}
